import json
import time

from ai import AIHandle
from command import ProjectHandle


def getNeedTranslationInfo(aiParamsPath):
    # 获取需要AI 处理的对象
    with open(aiParamsPath, 'r', encoding='utf-8') as f:
        aiParams = json.load(f)
    needTranslationInfo = aiParams.get('needTranslationInfo')
    return needTranslationInfo


def getAIInfo(aiParamsPath):
    # 获取需要AI 处理的对象
    with open(aiParamsPath, 'r', encoding='utf-8') as f:
        aiParams = json.load(f)
    needTranslationInfo = aiParams.get('aiAnswer')
    return needTranslationInfo


# 封装了使用ssh 执行命令的方法
def sshExcuteCommand(ssh, command):
    # 执行命令前 系统休整 1s
    time.sleep(1)
    # 执行命令
    print('执行命令:' + command)
    stdin, stdout, stderr = ssh.exec_command(command)

    # 获取命令输出
    command_output = stdout.read().decode('utf-8')
    print('命令返回:' + command_output)
    return command_output


# 从 commandParams 中获取对象和命令，然后执行命令，获取结果
def getInspectionCommandResult(ssh, commandParamsPath, aiParamsPath):
    # 获取对象
    with open(commandParamsPath, 'r', encoding='utf-8') as f:
        commandParams = json.load(f)
    # 获取需要AI 处理的对象
    with open(aiParamsPath, 'r', encoding='utf-8') as f:
        aiParams = json.load(f)

    aiInfo = aiParams.get('commandAIHandler')
    # 处理固定巡检命令
    fixedCommand = commandParams.get('fixedInfo')
    dicts = {}
    # 遍历fixedCommand，获取value 值，执行命令，再将返回结果放到 fixedCommand
    for key, value in fixedCommand.items():
        value = sshExcuteCommand(ssh, value)
        if value != '':
            # 在value 有值的请况下，才进行AI 分析
            if key in aiInfo:
                # 从aiParams 中获取key 对应的value，然后将value 传入AI 处理方法中
                premise = str(aiInfo.get(key))
                value = AIHandle.getListResult(premise + '\n' + value)
        dicts.setdefault(key, value)
    # 特殊巡检命令处理
    specialCommand = commandParams.get('specialInfo')
    for key, value in specialCommand.items():
        value = sshExcuteCommand(ssh, value)
        # 对查Project 命令进行列表组装
        if key.find('javaProjectInfo') != -1:
            value = ProjectHandle.javaProjectHandle(value)
            if value != '':
                # 在value 有值的请况下，才进行AI 分析
                if key in aiInfo:
                    premise = str(aiInfo.get(key))
                    value = AIHandle.getListResult(premise + '\n' + value)
        dicts.setdefault(key, value)
    return dicts
